/**
 * Created by duqingxiang on 17/5/25.
 */

var validateCodeFlag = false;
var captchaId='';
var captcha='';
// tobe config
var url_prefix= $("#url_prefix").val(); //测试环境
//var url_prefix="";    //真实环境
$(".vcode-btn").click(function(){

    if (validateCodeFlag) {
        weui.topTips("休息一下等会儿再发");
        return;
    }

    var phone = $("#validatePhone").val();
    var phoneValid = /^(((13[0-9]{1})|(15[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(phone);
    if (phone == null || phone == "") {
        weui.topTips("请输入手机号");
        return;
    }
    if(!phoneValid){
        weui.topTips("手机号输入格式有误");
        return;
    }

    $('#J_getCode').hide();
    $('#J_second').html('60');
    $('#J_resetCode').show();
    var clientId = $("#clientId").val();
    var $btn = $(this);
    captcha = $("#captchaCode").val();
    var url = url_prefix+"/api/v2/sms/wx/send";
    var param = {clientId:clientId};
    //getCode(this);
    axios.post(url,{
        phoneNum:phone,
        clientId:clientId,
        captchaId:captchaId,
        captcha:captcha
    }).then(function(response){
        if(response.data.flag){
            $('#J_getCode').show();
            $('#J_resetCode').hide();
            $('#J_captcha').show();
            getCaptcha();
        }else{
            resetCode();
            $('#J_captcha').hide();
            validateCodeFlag=true;
        }
        if(response.data.message.length>0){
            weui.topTips(response.data.message);
        }
    }).catch(function (error) {
        console.log(error)
    })
});


function getCaptcha() {
    axios.get(url_prefix+'/api/v2/sms/getCaptcha').then(function (response) {
        $("#captchaCode").val("");
        captchaId=response.data.captchaId;
        $('#J_img').attr("src",response.data.captchaWechatURL);
    })
}
/*获取验证码*/
var isPhone = 1;
function getCode(e){
    checkPhone(); //验证手机号码
    if(isPhone){
        resetCode(); //倒计时
        validateCodeFlag = false;
    }else{
        $('#validatePhone').focus();
    }

}
//验证手机号码
function checkPhone(){
    var phone = $('#validatePhone').val();
    var pattern = /^1[0-9]{10}$/;
    isPhone = 1;
    if(phone == '') {
        weui.topTips("请输入手机号码");
        isPhone = 0;
        return;
    }
    if(!pattern.test(phone)){
        weui.topTips("请输入正确的手机号码");
        isPhone = 0;
        return;
    }
}
//倒计时
function resetCode(){
    var second = 60;
    var timer = null;
    timer = setInterval(function(){
        second -= 1;
        if(second >0 ){
            $('#J_second').html(second);
        }else{
            clearInterval(timer);
            $('#J_getCode').show();
            $('#J_resetCode').hide();
            validateCodeFlag = false;
        }
    },1000);
}